#include "qresourcelistview.h"

#include "qresourcefilemodel.h"

#include <QItemDelegate>
#include <QPainter>

class ItemDelegate: public QItemDelegate
{
public :
    virtual QSize	sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const;

    virtual void	paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const;
};

QSize   ItemDelegate::sizeHint(const QStyleOptionViewItem &/*option*/, const QModelIndex &/*index*/) const
{
    return QSize(48,48);
}

void    ItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if(index.data(Qt::UserRole).toBool())
    {
        painter->fillRect(option.rect,QColor(128,128,128,80));
    }
    QItemDelegate::paint(painter,option,index);
}

QResourceListView::QResourceListView(AbstractCore *core, QWidget *parent):
    QListView(parent),
    m_core(core)
{
    setFocusPolicy(Qt::NoFocus);
    setFrameShape(QFrame::NoFrame);
    setIconSize(QSize(32, 32));
    setSpacing(1);
    setTextElideMode(Qt::ElideMiddle);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setResizeMode(QListView::Adjust);
    //setUniformItemSizes(true);

    m_model=new QResourceFileModel(m_core,this);
    setModel(m_model);

    setViewMode(IconMode);

    setItemDelegate(new ItemDelegate());

    connect(this,SIGNAL(pressed(QModelIndex)),this,SLOT(mousePressed(QModelIndex)));
}

QSize QResourceListView::ContentsSize()
{
    return contentsSize();
}

void QResourceListView::addFile(QString str)
{
    m_model->addFile(str);
}

void QResourceListView::removeFile(QString str)
{
    m_model->removeFile(str);
}

void QResourceListView::select(QString name)
{
    QString str=m_model->select();
    if(str!=name)
    {
        int index=m_model->findResource(str);
        if(index>=0)
        {
            m_model->setData(m_model->index(index),false,Qt::UserRole);
        }
        index=m_model->findResource(name);
        if(index>=0)
        {
            m_model->setData(m_model->index(index),true,Qt::UserRole);
        }
        emit selectChanged();
    }
    else
    {
        if(name=="")
        {
            emit selectChanged();
        }
    }

}

QString QResourceListView::getSelect()
{
    return m_model->select();
}

void QResourceListView::mousePressed(const QModelIndex &index)
{
    QString str=index.data(Qt::DisplayRole).toString();
    if(str!=getSelect())
    {
        select(str);
    }
}

void QResourceListView::clear()
{
    m_model->clear();
}
